<template>
  <template v-if="loaded">
    <ProForm
      ref="formRef"
      :model="formState"
      :items="items"
      :disabled="readonly"
      :onValuesChange="onValuesChange"
      :formColLayout="formColLayout()"
      :requiredMark="!readonly"
      class="pro-form-modal"
      v-bind="formProps"
    >
    </ProForm>
    <FooterButtons
      :formState="formState"
      :formRef="formRef"
      v-model:readonly="readonly"
      :serviceApi="_updateNtpConfig"
      @refresh="refresh"
      :fastConfig="fastConfig"
    />
  </template>
</template>

<script setup lang="tsx">
import { computed, nextTick, ref, shallowRef } from 'vue';
import dayjs from 'dayjs';
import { ProForm, ProFormProps } from '@/components/ProForm';
import { ItemProps } from '@/components/ProForm/interface';
import { getNtpConfig, updateNtpConfig } from '@/api/device';
import FooterButtons from './FooterButtons.vue';

defineOptions({
  name: 'Ntp',
});

interface Props {
  pageData: any;
  readonly?: any;
  fastConfig?: boolean;
}
const props = defineProps<Props>();
const loaded = ref(false);
const readonly = ref(props.readonly ?? true);
const formRef = shallowRef();
const formState = ref<Record<string, any>>({});
const column = 3;
const formColLayout = () => {
  const num = 24 / column;
  return { xs: num, sm: num, md: num, lg: num };
};
const formProps = computed<ProFormProps>(() => {
  return {
    labelCol: { span: 7 },
    wrapperCol: { span: 20 },
  };
});
const onValuesChange = (
  values: Record<string, any>,
  state: Record<string, any>,
) => {
  formState.value = {
    ...formState.value,
    ...state,
  };
  if (values.hasOwnProperty('ntpTime')) {
    nextTick(() => {
      state.ntpTime = state.ntpTime.replace(/[^0-9]/g, '');
    });
  }
};
const refresh = () => {
  loaded.value = false;
  nextTick(() => {
    loaded.value = true;
  });
};
const itemObj = (
  label: string,
  type: any,
  field: string,
  required: boolean = false,
  props?: any,
  layout?: any,
  rules: any = [],
): ItemProps => {
  return {
    label,
    type,
    field,
    props: {
      placeholder: `请${type == 'input' ? '输入' : '选择'}${label}`,
      allowClear: false,
      ...props,
    },
    rules: [
      {
        required,
        message: `请${type == 'input' ? '输入' : '选择'}${label}`,
        trigger: 'blur',
      },
      ...rules,
    ],
    ...layout,
  };
};
const itemRender = (title: string): ItemProps => {
  return {
    label: { title },
    type: 'input',
    field: 'h5',
    formItemRender() {
      return <h5 class='h5'>{title}</h5>;
    },
  };
};
const radioOptions = [
  { value: '0', label: '关闭' },
  { value: '1', label: '开启' },
];

const items = computed<ProFormProps['items']>(() => [
  itemRender('服务配置'),
  itemObj('自动对时服务', 'radio', 'isOpenNtp', true, {
    options: radioOptions,
    onChange: (e: any) => {
      if (e.target.value == 0) {
        formRef.value.setFiledValue('systemTime', undefined);
      }
    },
  }),
  itemRender('参数配置'),
  itemObj('对时服务地址', 'input', 'ntpAddress', false),
  itemObj(
    '对时频率',
    'input',
    'ntpTime',
    true,
    {
      addonAfter: 's',
    },
    undefined,
    [
      {
        message: '对时频率不能小于10s',
        validator: (rule: any, value: any, callback: any) => {
          if (value && Number(value) < 10) {
            return Promise.reject('对时频率不能小于10s');
          } else {
            return Promise.resolve();
          }
        },
        trigger: 'blur',
      },
    ],
  ),
  itemObj(
    '设置系统时间',
    'date',
    'systemTime',
    false,
    { showTime: true },
    {
      hide(state: any) {
        return state.isOpenNtp == 1 || state.isOpenNtp == undefined;
      },
    },
  ),
]);

props.pageData.ntpConfigsJson
  ? (() => {
      formState.value = JSON.parse(props.pageData.ntpConfigsJson);
      formState.value.systemTime = dayjs(formState.value.systemTime);
      loaded.value = true;
    })()
  : getNtpConfig(props.pageData.code).then((res: any) => {
      formState.value = res.data;
      formState.value.code = props.pageData.code;
      formState.value.systemTime = dayjs(formState.value.systemTime);
      loaded.value = true;
    });

const _updateNtpConfig = async (params: any) => {
  const systemTime = params.systemTime
    ? dayjs(params.systemTime).valueOf()
    : undefined;
  await updateNtpConfig({ ...params, systemTime });
};
defineExpose({
  async save() {
    const data = await formRef.value.validate();
    const systemTime = data.systemTime
      ? dayjs(data.systemTime).valueOf()
      : undefined;
    props.pageData.ntpConfigsJson = JSON.stringify({ ...data, systemTime });
  },
});
</script>
